package com.bicon.botu.mall.component.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.component.common.BrowsingHistoryConstants;
import com.bicon.botu.mall.component.mapper.ComponentBrowsingHistoryMapper;
import com.bicon.botu.mall.component.dto.BrowsingHistoryDTO;
import com.bicon.botu.mall.component.entity.BrowsingHistory;
import com.bicon.botu.mall.component.service.IComponentBrowsingHistoryService;
import com.bicon.botu.mall.component.vo.ProductListVo;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.common.utils.StringUtils;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

import static com.alibaba.fastjson.JSON.parseArray;


/**
 * @Author 李双喜
 * @Date 2017/8/3 12:45
 */
@Slf4j
@Service
@Transactional
public class ComponentBrowsingHistoryImpl extends ServiceImpl<ComponentBrowsingHistoryMapper, BrowsingHistory> implements IComponentBrowsingHistoryService {
    @Autowired
    private ComponentBrowsingHistoryMapper componentBrowsingHistoryMapper;

    @Autowired
    private RedisHandler redisHandler;

    /**
     * 添加浏览记录
     * @param userId      用户id
     * @param type        类型
     * @param historyJson 历史记录json
     * @return
     */
    @Override
    public boolean insertHistory(String userId, String type, String historyJson) {
        //先取到缓存，循环转成dto
        List<String> browsingHistorys = redisHandler.getGlobalRedisTemplate().getList(BrowsingHistoryConstants.REDIS_KEY,":" + type + ":" + userId);
        List<BrowsingHistoryDTO> browsingHistoryDTOs = new ArrayList<>();
        for(String browsingHistory: browsingHistorys){
            browsingHistoryDTOs.add(JsonUtil.fromJson(browsingHistory,BrowsingHistoryDTO.class));
        }
        List<BrowsingHistoryDTO> list = parseArray(historyJson, BrowsingHistoryDTO.class);
        list.addAll(browsingHistoryDTOs);
        Collections.sort(list, Comparator.comparing(BrowsingHistoryDTO::getCreateTime).reversed());
        List<BrowsingHistory> browsingHistoryList = new ArrayList<>();//BeanMapper.mapList(list, BrowsingHistory.class);
        List<String> browsingHistoryStringList = new ArrayList<>();
        for (BrowsingHistoryDTO dto : list) {
            BrowsingHistory browsingHistory = new BrowsingHistory();
            browsingHistory.setId(dto.getId());
            browsingHistory.setType(type);
            browsingHistory.setUserId(userId);
            browsingHistory.setCreateTime(dto.getCreateTime());
            browsingHistoryList.add(browsingHistory);
            //只是将需要的数据转换成json然后再放入缓存中即可
            browsingHistoryStringList.add(JsonUtil.toJson(dto));
        }
        redisHandler.getGlobalRedisTemplate().remove(BrowsingHistoryConstants.REDIS_KEY, ":" + type + ":" + userId);
        redisHandler.getGlobalRedisTemplate().cacheList(BrowsingHistoryConstants.REDIS_KEY, ":" + type + ":" + userId, browsingHistoryStringList);
        return insertBatch(browsingHistoryList);
    }
    /**
     * 批量删除
     *
     * @param browsingHistoryIdJson 多个浏览历史id
     * @param type                  类型
     * @param userId                用户id
     * @return
     */
    @Override
    public BaseResult deleteHistory(String browsingHistoryIdJson, String type, String userId) {
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(browsingHistoryIdJson)) {
            //数组转成list
            list = Arrays.asList(browsingHistoryIdJson.split(","));
        }
        boolean result = this.deleteBatchIds(list);
        redisHandler.getGlobalRedisTemplate().remove(BrowsingHistoryConstants.REDIS_KEY, ":" + type + ":" + userId);
        if (result) {
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        }
        return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
    }


    /**
     * 清空所有
     * @param userId   用户id
     * @param type     类型
     * @return         BaseResult
     */
    @Override
    public BaseResult deleteAll(String userId, String type) {
        List<BrowsingHistory> browsingHistoryList = componentBrowsingHistoryMapper.selectList(new EntityWrapper<BrowsingHistory>().eq("user_id", userId));
        if (CollectionUtils.isEmpty(browsingHistoryList)) {
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
        boolean result = this.deleteBatchIds(browsingHistoryList);
        redisHandler.getGlobalRedisTemplate().remove(BrowsingHistoryConstants.REDIS_KEY, ":" + type + ":" + userId);
        if (result) {
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        }
        return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
    }

    /**
     * 查询浏览历史
     *
     * @param userId 用户id    用户id
     * @param type   类型      类型
     * @return                 BaseResult
     */
    @Override
    public BaseResult getBrowsingHistory(String userId, String type) {
        //在浏览历史redis里面查询BrowsingHistory对象
        List<String> list1 = redisHandler.getGlobalRedisTemplate().getList(BrowsingHistoryConstants.REDIS_KEY, ":" + type + ":" + userId);
        //不超过20条
        int u = list1.size() > 20 ? 20 : list1.size();
        List<Object> list = new ArrayList<>();
        //遍历
        for (int i = 0; i < u; i++) {
            //将String 转对象
            BrowsingHistory browsingHistory = JSONObject.parseObject(list1.get(i), BrowsingHistory.class);
            if (type.equals(BrowsingHistoryConstants.MALL)) {
                //将String 转 对象
                ProductListVo vo = JSONObject.parseObject(redisHandler.getGlobalRedisTemplate().getStringValue(BrowsingHistoryConstants.PRODUCT_INFO, browsingHistory.getId()), ProductListVo.class);
                list.add(vo);
            }
        }
        if(!CollectionUtils.isEmpty(list)){
            return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200,list);
        }
        return new BaseResult(Constants.RESPONSE_CODE_602,Constants.RESPONSE_MESSAGE_602);
    }
}
